<?php

/**
 * 商品详细页
 */
define('IN_ECS', true);
require(dirname(__FILE) . '/includes/init.php');

$goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;
$act = $_REQUEST['act'];

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */
/* 配送区域 */
assign_region();

/* 销量 */
$sql = 'SELECT SUM(goods_number) ' .
'FROM ' . $GLOBALS['ecs']->table('order_goods') . " WHERE goods_id = '$goods_id'" ;
$sales_count = $GLOBALS['db']->getOne($sql);

/* 获得商品的信息 */
$goods = get_goods_info($goods_id);

if ($goods === false || !$goods['is_on_sale'])
{
    errorMsg('没有该商品');
    exit;
}
else
{
    $shop_price   = $goods['shop_price'];
    $linked_goods = get_linked_goods($goods_id);

    if('detail' === $act){

        // $properties = get_goods_properties($goods_id);  // 获得商品的规格和属性   (颜色。。。)
        // var_dump($properties['spe']);                              // 商品规格
        
        /* 最组合特殊处理 */
        if ($goods['cat_id'] == 101) 
        { 
            $goods_number = 10000;
            /* 最组合商品信息处理 */
            if($goods['compose_note'])
            {
                $properties = array();
                $compose_colors = array();
                foreach (explode(',',$goods['compose_note']) as $key => $value) 
                {
                    $compose_goods[$key]['compose_goods_sku'] = explode('X',current(explode('*',$value)));
                    $compose_goods[$key]['goods_number'] = end(explode('*',$value));
                    foreach ($compose_goods[$key]['compose_goods_sku'] as $k => $v) 
                    {
                        $sql = "SELECT ga.* FROM " . $ecs->table('goods_attr') . " ga LEFT JOIN " . $ecs->table('goods') . " g ON g.goods_id = ga.goods_id WHERE ga.attr_id = 1 AND g.goods_sku = $v";
                        if($row = $db->getRow($sql))
                        {
                            $properties = get_goods_properties($row['goods_id']);
                            $compose_colors = array_merge($compose_colors,$properties['spe'][1]['values']);
                            $compose_colors_number = $compose_goods[$key]['goods_number'];
                        }
                        else
                        {
                            $sql = "SELECT g.*,gs.* FROM " . $ecs->table('goods') . " g LEFT JOIN " . $ecs->table('goods_stock') . " gs ON gs.goods_sku = g.goods_sku  WHERE g.goods_sku = $v";
                            $row = $db->getRow($sql);
                            $goods_number = floor($row['goods_number']/$compose_goods[$key]['goods_number'])<$goods_number?floor($row['goods_number']/$compose_goods[$key]['goods_number']):$goods_number;
                        }
                    }
                }
                var_dump( $compose_colors);                              // 最组合颜色
                var_dump( $compose_colors_number);                       // 最组合颜色自选数量 

            }
            if($goods_number>0)
            {
                $sql = "UPDATE " . $ecs->table('goods_stock') . " SET goods_number = $goods_number WHERE goods_sku = $goods[goods_sku]";
                $db->query($sql);
                $sql = "SELECT goods_number FROM " . $ecs->table('cart') . " WHERE goods_id = $goods[goods_id] AND goods_attr_id = 0";
                $goods_number = $goods_number-intval($db->getOne($sql));
            }
            $goods['goods_number'] = $goods_number;
            
            $gallary = get_goods_gallery($goods_id,20);                    // 商品相册
        }

        else      //普通商品的相册
        {
            $gallary = get_goods_gallery($goods_id, 5);                    // 商品相册
        }

        /* 商品详情 */
        $normal['goodsId'] = $goods['goods_id'];
        $normal['goodsSku'] = $goods['goods_sku'];
        $normal['goodsName'] = urlencode($goods['goods_name']);
        $normal['shopPrice'] = $goods['shop_price'];
        $normal['marketPrice'] = $goods['market_price'];
        $normal['promotePrice'] = $goods['promote_price'];
        //$normal['remain'] = $goods['remain'];
        //详细描述图
        $reg = '/\/images\/upload\/Image\/[0-9\/]*.jpg/';
        preg_match_all($reg, $goods['goods_desc'], $res);
        for ($i=0; $i < count($res[0]); $i++) { 
              $normal['goodsDesc'][] = $_SERVER['HTTP_HOST'] . $res[0][$i];
        }  
        //商品图
        for($i = 0; $i < count($gallary); $i++){
            $normal['goodsImage'][] = $_SERVER['HTTP_HOST'] . '/' . $gallary[$i]['img_url'];
        }
        $normal['isOnSale'] = $goods['is_on_sale'];
        $normal['isPromote'] = $goods['is_promote'];
        $normal['goodsNumber'] = $goods['goods_number'];

        /* 关联商品 */
        $normal['haveRelevance'] = (count($linked_goods) == 0)? 0 :1;

        /* 商品的规格和属性 */
        $properties = get_goods_properties($goods_id);  // 获得商品的规格和属性   (颜色。。。)
        $attribute = array();
        if(count($properties['spe'])==0){
            $normal['haveAttribute'] = 0;
        }else{
            $normal['haveAttribute'] = 1;
            for ($i=0; $i < count($properties['spe'][1]['values']); $i++) { 
                $attribute[$i]['label'] = $properties['spe'][1]['values'][$i]['label'];
                $attribute[$i]['goodsAttrSku'] = $properties['spe'][1]['values'][$i]['goods_attr_sku'];
                $attribute[$i]['bgCode'] = $properties['spe'][1]['values'][$i]['bg_code'];
                $attribute[$i]['goodsNumber'] = $properties['spe'][1]['values'][$i]['goods_number'];
            }
        }
        
        /* 输出response */
        $linked_goods = tourlencode($linked_goods);
        $attribute = tourlencode($attribute);
        $response['response'] = 'goodsDetail';
        $response['normal'] = $normal;
        $response['region'] = tourlencode($_SESSION['consignee']);
        $response['relevanceGoods'] = $linked_goods;
        $response['attribute'] = $attribute;
        echo tourldecode($response);
        exit();
    }

    if('collect' === $act)
    {
        echo $act;
        exit();
    }
    
       
    if('comment' === $act)
    {
        $count = get_comment_count($goods_id);          // 评论总数
        $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
        $comments = array();
        if ($count !==0 && $count>=($page-1)*5) {            //5是page_size在lib_main中
            $cmt = assign_comment($goods['goods_id'],0,$page);      //lib_main

            foreach ($cmt['comments'] as $row) {
                $goodsComment['username'] = urlencode($row['username']);
                $goodsComment['content'] = urlencode($row['content']);
                $goodsComment['content_more'] = urlencode($row['content_more']);    
                $goodsComment['commentTime'] = urlencode($row['add_time']);
                $comments[] = $goodsComment;
            }
        }
        else{
            errorMsg('分页不存在');
        } 
        $response = array('response'=>'goodsComment', 'goodsComment'=>$comments, 'listCount'=>$count);
        echo tourldecode($response);
        exit();
    }
 
    /* 最组合特殊处理 */
    if ($goods['cat_id'] == 101) { 
        $goods_number = 10000;
        /* 最组合商品信息处理 */
        if($goods['compose_note']){
            $properties = array();
            $compose_colors = array();
            foreach (explode(',',$goods['compose_note']) as $key => $value) {
                $compose_goods[$key]['compose_goods_sku'] = explode('X',current(explode('*',$value)));
                $compose_goods[$key]['goods_number'] = end(explode('*',$value));
                foreach ($compose_goods[$key]['compose_goods_sku'] as $k => $v) {
                    $sql = "SELECT ga.* FROM " . $ecs->table('goods_attr') . " ga LEFT JOIN " . $ecs->table('goods') . " g ON g.goods_id = ga.goods_id WHERE ga.attr_id = 1 AND g.goods_sku = $v";
                    if($row = $db->getRow($sql)){
                        $properties = get_goods_properties($row['goods_id']);
                        $compose_colors = array_merge($compose_colors,$properties['spe'][1]['values']);
                        $compose_colors_number = $compose_goods[$key]['goods_number'];
                    }else{
                        $sql = "SELECT g.*,gs.* FROM " . $ecs->table('goods') . " g LEFT JOIN " . $ecs->table('goods_stock') . " gs ON gs.goods_sku = g.goods_sku AND gs.area_id = $_SESSION[area_id] WHERE g.goods_sku = $v";
                        $row = $db->getRow($sql);
                        $goods_number = floor($row['goods_number']/$compose_goods[$key]['goods_number'])<$goods_number?floor($row['goods_number']/$compose_goods[$key]['goods_number']):$goods_number;
                        // if($goods_number == 0) die($v);
                    }
                }
            }
            var_dump( $compose_colors);                              // 最组合颜色
            var_dump( $compose_colors_number);                       // 最组合颜色自选数量
            exit();
        }
        if($goods_number>0){
            $sql = "UPDATE " . $ecs->table('goods_stock') . " SET goods_number = $goods_number WHERE goods_sku = $goods[goods_sku] AND area_id = $_SESSION[area_id]";
            $db->query($sql);
            $sql = "SELECT goods_number FROM " . $ecs->table('cart') . " WHERE goods_id = $goods[goods_id] AND goods_attr_id = 0 AND session_id = '".SESS_ID."'";
            $goods_number = $goods_number-intval($db->getOne($sql));
        }
        $goods['goods_number'] = $goods_number;
        
        $smarty->assign('pictures',            get_goods_gallery($goods_id,20));                    // 商品相册
    }else{
        $smarty->assign('pictures',            get_goods_gallery($goods_id));                    // 商品相册
    }
    // $smarty->assign('bought_goods',        get_also_bought($goods_id));                    //购买了该商品的用户还购买了哪些商品

}

/**
 * 获得指定商品的关联商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{

    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_img ' .
            'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . 
            'LEFT JOIN ' . $GLOBALS['ecs']->table('link_goods') . ' AS lg ' . 
                "ON g.goods_id = lg.link_goods_id " . 
            "WHERE lg.goods_id = '$goods_id' AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.is_on_sale = 1 ORDER BY g.goods_id ASC";

    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goodsId']     = $row['goods_id'];
        $arr[$row['goods_id']]['goodsName']   = $row['goods_name'];
        $return[] = $arr[$row['goods_id']];
    }

    return $return;
}